package com.it.emall.service.impl;

import com.it.emall.domain.AdminUser;
import com.it.emall.domain.Comments;
import com.it.emall.mapper.CommentsMapper;
import com.it.emall.service.CommentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CommentsServiceImpl implements CommentsService {

    @Autowired
    private CommentsMapper commentsMapper;

    @Override
    public int addComment(int userId, int recipeId, String content) {

        AdminUser user = commentsMapper.getUserInfoById(userId);
        if (user == null) {
            return -1;  // 用户不存在
        }
        // 获取头像和用户名
        String avatar = user.getAvatar();
        String username = user.getUsername();

        // 添加评论
        int result = commentsMapper.addComment(userId, recipeId,username, content, avatar );
        return result == 1 ? 0 : -1;  // 如果插入成功，返回0，否则返回-1
    }

    @Override
    public List<Comments> getCommentsByRecipe(int recipeId) {
        // 获取指定食谱的所有评论
        return commentsMapper.findCommentsByRecipeId(recipeId);
    }

    @Override
    public int deleteComment(int userId, int commentId) {
        // 先检查评论是否属于该用户
        Comments comment = commentsMapper.findCommentById(commentId);
        if (comment != null && comment.getUserId() == userId) {
            int result = commentsMapper.deleteComment(commentId);
            return result == 1 ? 0 : -1;  // 如果删除成功，返回0，否则返回-1
        }
        return -1;  // 评论不属于该用户，返回-1
    }
}
